<?php

namespace tmcore\services\crud;

use think\helper\Str;

class UtilService
{
    /**
     * 下划线转驼峰(首字母小写)
     *
     * @param string $value
     * @return string
     */
    public static function camel(string $value): string
    {
        return Str::camel($value);
    }

    /**
     * 下划线转驼峰(首字母大写)
     *
     * @param string $value
     * @return string
     */
    public static function studly(string $value): string
    {
        return Str::studly($value);
    }

    /**
     * 驼峰转下划线
     *
     * @param string $value
     * @return string
     */
    public static function snake(string $value): string
    {
        return Str::snake($value);
    }

    /**
     * 字符串转小写
     *
     * @param string $value
     * @return string
     */
    public static function lower(string $value): string
    {
        return Str::lower($value);
    }

    /**
     * 首字母大写
     *
     * @param string $value
     * @return string
     */
    public static function ucwords(string $value): string
    {
        $value = '_'. str_replace('_', " ", strtolower($value));
        return ucwords(ltrim(str_replace(" ", "", ucwords($value)), '_' ));
    }

    /**
     * 首字母小写
     *
     * @param string $value
     * @return string
     */
    public static function lcfirst(string $value): string
    {
        return lcfirst($value);
    }

    /**
     * 文件夹不存在则创建
     * @param string $path
     */
    public static function checkDir(string $path)
    {
        !is_dir($path) && mkdir($path, 0755, true);
    }

    /**
     * 获取忽略的字段
     * @return string[]
     */
    public static function getIgnoreFields () {
        return ['create_time', 'update_time', 'delete_time'];
    }

    /**
     * 获取无前缀数据表名
     * @param $tableName
     * @return mixed|string
     */
    public static function get_no_prefix_table_name($tableName)
    {
        $tablePrefix = config('database.connections.mysql.prefix');
        $prefixIndex = strpos($tableName, $tablePrefix);
        if ($prefixIndex !== 0 || $prefixIndex === false) {
            return $tableName;
        }
        $tableName = substr_replace($tableName, '', 0, strlen($tablePrefix));
        return trim($tableName);
    }

    /**
     * 根据表名查询表信息
     *
     * @param array $tableParams (表名集)
     * @return array
     */
    public static function queryTablesByName(array $tableParams): array
    {
        $InArray = "(";
        foreach ($tableParams as $k => $tableParam) {
            $InArray .= $k > 0 ? ',' : '';
            $InArray .= "'".$tableParam['name']."'";
            if ($k >= count($tableParams)-1) {
                $InArray .= ")";
            }
        }

        $tables = app('db')->query('SHOW TABLE STATUS WHERE name in '.$InArray);
        $collection = [];
        foreach ($tables as $item) {
            $collection[] = [
                'name'        => $item['Name']    ?? $item['name'],
                'engine'      => $item['Engine']  ?? $item['engine'],
                'comment'     => $item['Comment'] ?? $item['comment'],
                'create_time' => $item['Create_time'] ?? $item['create_time'],
            ];
        }

        return $collection;
    }

    /**
     * 根据表名查询表字段
     *
     * @param string $tableName (表名称)
     * @return array
     */
    public static function queryColumnsByName(string $tableName): array
    {
        $tablePrefix = env('database.prefix', '');
        $tableNameMy = str_replace($tablePrefix, '', $tableName);
        return app('db')->name($tableNameMy)->getFields();
    }

    /**
     * 获取字段列主键
     *
     * @param array $columns
     * @return string
     */
    public static function getPk(array $columns): string
    {
        foreach ($columns as $item) {
            if ($item['is_pk']) {
                return $item['column_name'];
            }
        }

        return 'id';
    }

    /**
     * 生成tab
     * @param int $num
     * @return string
     */
    public static function tab(int $num = 1): string
    {
        return str_pad('', 4 * $num);
    }

    /**
     * 设置空额占位符
     * @param string $content
     * @param string $space
     * @return string
     */
    public static function setBlankSpace($content, $space)
    {
        $content = explode(PHP_EOL, $content);
        foreach ($content as $line => $text) {
            $content[$line] = $space . $text;
        }
        return (implode(PHP_EOL, $content));
    }

    /**
     * 替换内容
     * @param $search
     * @param $replace
     * @param $template
     * @param $is_path
     * @return string|string[]
     */
    public static function replaceFileContent($search, $replace, $template, $is_path = true)
    {
        return str_replace($search, $replace, $is_path?file_get_contents($template):$template);
    }

    /**
     * 初始化字段搜索条件类型
     *
     * @param array $column
     * @return string
     */
    public static function handleQueryType(array $column): string
    {
        if (in_array($column['name'], ['create_time', 'update_time', 'delete_time'])) {
            return 'between';
        } elseif ($column['name'] == 'start_time') {
            return '>=';
        } elseif ($column['name'] == 'end_time') {
            return '<=';
        } elseif (in_array($column['name'], ['title', 'name', 'username', 'account'])) {
            return 'like';
        } elseif (str_starts_with($column['name'], 'is_')) {
            return '=';
        }
        return '=';
    }

    /**
     * 初始化字段表单类型
     *
     * @param array $column (列信息)
     * @return string
     */
    public static function handleFormType(array $column): string
    {
        if (in_array($column['name'], ['create_time', 'update_time', 'delete_time', 'start_time', 'end_time'])) {
            return 'datePicker';
        } elseif (str_starts_with($column['name'], 'is_')) {
            return 'radio';
        } elseif (in_array($column['type'], ['float', 'double', 'decimal', 'tinyint', 'smallint', 'mediumint', 'int', 'integer', 'bigint'])) {
            return 'number';
        } elseif (in_array($column['type'], ['date', 'time', 'year', 'datetime', 'timestamp'])) {
            return 'datePicker';
        }
        return 'input';
    }

}